<template>
	<view class="popup-bottom" @touchmove.stop.prevent="moveHandle" v-if="show">
	  <view class="popup-bg" @click="cancel"></view>
			<view class="popup-content">
				<view class="recorder">
					<view class="re-top" v-if="showTop">
						<view class="re-cancel" @tap.stop="cancel">取消</view>
						<view class="re-confirm" :style="{color: theme}" @click="confirm">{{ confirmText }}</view>
					</view>
					<text class="title">{{ finish ? '点击播放' : '长按录制语音,最多录制'+maximum+'秒' }}</text>
					<view class="recorder-box"  v-show="!finish"  @click="handle" @longpress="onStartRecoder"  @touchend="onEndRecoder">
						<u-circle-progress active-color="#eeeeee" :duration="0" :percent="calcProgress">
							<view class="u-progress-content">
								<image src="/static/sound-recording/voice.png" mode="aspectFit" :style="{width: width,height: height}"></image>
							</view>
						</u-circle-progress>
					</view>
					<view class="recorder-box" v-show="finish"  @tap.stop="playVoice">
						<u-circle-progress :active-color="theme" :duration="0" :percent="playProgress">
							<view class="u-progress-content">
								<image src="/static/sound-recording/play.png" mode="aspectFit" :style="{width: width,height: height}" v-if="!playStatus"></image>
								<image src="/static/sound-recording/pause.png" mode="aspectFit" :style="{width: width,height: height}" v-else></image>
							</view>
						</u-circle-progress>
					</view>
					<text class="now-date">{{ reDate }}</text>
					<view @click="reset" v-if="showTop">重新录制</view>
				</view>
			</view>
		</view>
	</view>	
</template>

<script>
  import uCircleProgress from '../u-circle-progress/u-circle-progress.vue'
  const recorderManager = uni.getRecorderManager();
  const innerAudioContext = uni.createInnerAudioContext();
	export default {
		components: {
			uCircleProgress
		},
		props: {
			show:{
				type: Boolean,
				default: false
			},
			width: {
				type: String,
				default: '60rpx'
			},
			height: {
				type: String,
				default: '60rpx'
			},
			showTop: {
				type: Boolean,
				default: true
			},
			maximum: {
				type: [Number, String],
				default: 0
			},
			duration: {
				type: Number,
				default: 1000
			},
			theme: {
				type: String,
				default: '#32b99d'
			},
			confirmText: {
				type: String,
				default: '完成'
			}
		},
		data() {
			return {
				reDate: '00:00',
				sec: 0,
				min: 0,
				finish: false,
				voicePath: '',
				playProgress: 100,
				playTimer: null,
				timer: null,
				playStatus: false,
				obj:'',
				needTestPlay:false,
			};
		},
    created () {
      // 监听
      this.onMonitorEvents()
	  //innerAudioContext.src = 'http://qny-daka.jnmsywl.com/neworder.mp3';
	  /* innerAudioContext.onPlay(() => {
	    console.log('开始播放',innerAudioContext);
	  }); */
	   var that = this;
	  setTimeout(function(){
		/* var tempFilePath = 'http://qny-daka.jnmsywl.com/neworder.mp3';
		  that.voicePath = tempFilePath
		  //console.log(that.voicePath)
		  innerAudioContext.src = tempFilePath */
	  },3000)
	  
    },
    computed: {
      // 录制时间计算
      calcProgress () {
		  return 100;
			//return (this.sec + (this.min * 60)) / this.maximum * 100
      }
    },
    methods: {
		//动态修改链接
		initAudioSrc(info){
			var src = info.value?info.value:'';
			if(!src || src == '')
			{
				this.reset();
				//innerAudioContext.src = ''
			}else{
				this.voicePath = src
				innerAudioContext.src = src
				this.min = info.min;
				this.sec = info.sec;
				this.reDate = info.reDate;
				//this.resetDate()
				this.finish = true;
				this.playStatus = false
				
			}
			
		},
      // 完成事件
      confirm () {
		let _min = this.min
        if (_min < 10) _min = '0' + _min;
        let _sec = this.sec
        if (_sec < 10) _sec = '0' + _sec;
        this.$emit('confirm', {
			path:this.voicePath,
			reDate:_min + ':' + _sec,
			min:this.min,
			sec:this.sec
		})
		this.cancel();
      },
      // 取消事件
      cancel () {
        if (!innerAudioContext.paused) {
          innerAudioContext.stop()
        }
        this.$emit('cancel')
      },
      // 点击事件
      handle () {
		this.$emit('click')
      },
      // 重新录制
      reset() {
		  if (!innerAudioContext.paused) {
		    innerAudioContext.stop()
		  }
			this.voicePath = ''
			this.min = 0
			this.sec = 0
			this.reDate = '00:00'
			this.playProgress = 100
			this.finish = false
			this.$emit('reset')
      },
      // 播放暂停录音
      playVoice() {
		  //this.obj = JSON.stringify(innerAudioContext.paused)
		  //this.voicePath = 'http://qny-daka.jnmsywl.com/neworder.mp3';
		  if(!this.voicePath)
		  {
			  this.$api.msg('未获取到语音');return ;
		  }
		  if(!innerAudioContext.src)
		  {
			  innerAudioContext.src = this.voicePath;
		  }
          if(innerAudioContext.paused) {
			  
			innerAudioContext.play()
            this.playStatus = true
        } else {
			innerAudioContext.stop();
			this.playStatus = false
        }
        this.$emit('playVoice', innerAudioContext.paused)
      },
      // 录制结束
      onEndRecoder () {
		 recorderManager.stop()
      },
      // 开始录制
      onStartRecoder () {
		  var that = this;
		  that.$api.checkScopeRecord(function(e){
		  	recorderManager.start({
				duration: that.maximum * 1000,
		  		format:'mp3'
		  	})
		  	that.$api.loadingMsg('正在调用麦克风');
		  })
      },
      // 监听
      onMonitorEvents () {
		var that = this;
        // 录制开始
        recorderManager.onStart(() => {
			  uni.showLoading({
				title: '录制中...'
			  })
			  this.startDate()
			  this.$emit('start')
        })
        // 录制结束
        recorderManager.onStop(({ tempFilePath }) => {
			//this.obj = tempFilePath;
			innerAudioContext.src = tempFilePath
			that.voicePath = tempFilePath;
			clearInterval(this.timer)
			uni.hideLoading()
			//模拟播放 不然无法获取到有效时长
			that.needTestPlay = true;
			innerAudioContext.volume = 0 // 无音播放
			innerAudioContext.play()
			//模拟播放结束
			this.$emit('end')
        })
		recorderManager.onError((e) => {
			//this.obj = tempFilePath;
			this.$api.msg('未获取到麦克风');
			uni.hideLoading()
		})
		
		innerAudioContext.onCanplay((e) => {
			innerAudioContext.duration;
			console.log('onCanplay准备就绪',innerAudioContext.duration)
			
		});
		
		/* innerAudioContext.onCanplay((e) => {
			
			innerAudioContext.duration;
			// 必须。不然也获取不到时长
			setTimeout(function(){
				let duration = innerAudioContext.duration
				if(duration < 1)
				{
					that.$api.msg('录音时长不能小于1秒');
					that.reset()
					return ;
				}
				//console.log('获取时长',duration)
				that.voicePath = innerAudioContext.src;
				that.finish = true
				let _min = Math.floor(duration / 60)
				that.min = _min;
				if (_min < 10) _min = '0' + _min;
				let _sec = Math.floor(duration%60)
				that.sec = _sec;
				if (_sec < 10) _sec = '0' + _sec;
				that.reDate = _min + ':' + _sec
				//console.log('延迟一段时间',innerAudioContext.duration); // 401.475918
			},100)
		}); */
        // 播放进度
        innerAudioContext.onTimeUpdate(() => {
			console.log(that.needTestPlay)
			if(that.needTestPlay == true)
			{
				//录制完成后需要模拟播放 来获取时间  只要获取到时间就结束播放
				that.needTestPlay = false;
				let duration = innerAudioContext.duration
				if(duration < 1)
				{
					that.$api.msg('录音时长不能小于1秒');
					that.reset()
					return ;
				}
				//console.log('获取时长',duration)
				//that.voicePath = innerAudioContext.src;
				that.finish = true
				let _min = Math.floor(duration / 60)
				that.min = _min;
				if (_min < 10) _min = '0' + _min;
				let _sec = Math.floor(duration%60)
				that.sec = _sec;
				if (_sec < 10) _sec = '0' + _sec;
				that.reDate = _min + ':' + _sec;
				innerAudioContext.stop();
				innerAudioContext.volume = 1; // 无音播放
				return ;
			}
          let totalDate = innerAudioContext.duration
          let nowTime = innerAudioContext.currentTime
          let surplus = totalDate - nowTime
          //this.playProgress = surplus / totalDate * 100
          let _min = Math.floor(surplus / 60)
          if (_min < 10) _min = '0' + _min;
          let _sec = Math.floor(surplus%60)
          if (_sec < 10) _sec = '0' + _sec;
          this.reDate = _min + ':' + _sec
        })
        // 播放暂停
        innerAudioContext.onPause(() => {
           this.resetDate()
           this.playStatus = false
           this.$emit('onPause') 
        })
		// 播放暂停
		innerAudioContext.onEnded(() => {
			
		   this.resetDate()
		  this.playStatus = false
		  this.$emit('onEnded') 
		})
        // 播放停止
        innerAudioContext.onStop(() => {
          this.resetDate()
          this.playStatus = false
          this.$emit('onStop') 
        })
      },
	  //重置语音
	  restVoice(){
		  
	  },
      // 录音计时
      startDate () {
        clearInterval(this.timer)
        this.sec = 0
        this.min = 0
        this.timer = setInterval(() => {
          this.sec += this.duration / 1000
          if (this.sec >= 60) {
            this.min ++
            this.sec = 0
          }
          this.resetDate()
        }, this.duration)
      },
      // 播放时间
      resetDate () {
        let _s = this.sec < 10 ? '0' + parseInt(this.sec) : parseInt(this.sec)
        let _m = this.min < 10 ? '0' + this.min : this.min
        this.reDate = _m + ':' + _s
      }
    }
	}
</script>

<style lang="scss">
	.popup-bottom {
	  position: fixed;
	  bottom: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  z-index: 10;
	  display: flex;
	  flex-direction: column;
	  .popup-bg {
	    position: fixed;
	    left: 0;
	    top: 0;
	    width: 100%;
	    height: 100%;
	    background: rgba(0,0,0,0.5);
	  }
	  .popup-content {
	    height: 40%;
	    margin-top: auto;
	    background-color: #fff;
	    position: relative;
	    z-index: 11;
	  }
	  }
.recorder {
  position: relative;
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: #fff;
  font-size: 24rpx;
  width: 100%;
  .re-top {
    display: flex;
    justify-content: space-between;
    padding: 10rpx 20rpx;
    width: 100%;
    font-size: 28rpx;
    box-sizing: border-box;
  }
  .title {
    font-size: 36rpx;
    color: #333;
    padding: 20rpx 0 30rpx;
  }
  .recorder-box {
    position: relative;
  }
  .now-date {
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}

</style>
